<?php
/**
 * Created by PhpStorm.
 * User: wangan
 * Date: 2016/12/15
 * Time: 17:00
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Http\Service\CategoryService;
use Illuminate\Http\Request;

class CategoryController extends  Controller
{

    public function index(Request $request){
        $categorys = CategoryService::getAllCategoryGroupby();
        return view('admin.category.index',[
            'categorys'=>$categorys
        ]);
    }

    public function create(Request $request){
        $cid = $request->input('cid');
        return view('admin.category.create',[
            'cid'=>$cid
        ]);
    }

    public function doCreate(Request $request){
        $this->categoryValidate($request);
        $data = $request->input('info');
        if(CategoryService::createOneCategory($data)){
            return redirect('/admin/category/index?cid='.$data['cid']);
        }else{
            return redirect()->back();
        }
    }

    public function edit(Request $request){
        $catId = $request->input('catId');
        $catInfo = CategoryService::getOneCategory($catId);
        return view('admin.category.edit',[
            'info'=>$catInfo,
        ]);
    }

    public function doEdit(Request $request){
        $this->categoryValidate($request);
        $data = $request->input('info');
        if(CategoryService::updateOneCategory($data)){
            return redirect('/admin/category/index');
        }else{
            return redirect()->back();
        }
    }

    public function deleteOneCategory(Request $request){
        $catId=$request->input('catId');
        if(CategoryService::checkHasChild($catId)){
            return response()->json([
                'code' => 417,
                'message' => '请先删除该权限所有子菜单！'
            ]);
        }
        if(CategoryService::deleteCategory($catId)){
            return response()->json([
                'code' => 200,
                'message' => '操作成功！'
            ]);
        }
        else{
            return response()->json([
                'code' => 500,
                'message' => '操作失败！请重试!'
            ]);
        }
    }

    private function categoryValidate(Request $request){
        return $this->validate($request,[
            'info.name'=>'required',
            'info.label'=>'required',
        ],[
            'required'=>':attribute不能为空',
            'unique'=>':attribute已存在',
            'integer'=>':attrbute必须为整数'
        ],[
            'info.name'=>'栏目路由名称',
            'info.label'=>'栏目名称',
        ]);
    }

}